<!-- 下拉选择器 -->
<template>
  <el-select
    v-model="valueModal"
    :filterable="filterable"
    remote
    clearable
    :remote-method="remoteMethod"
    :placeholder="placeholder"
    v-bind="$attrs"
    style="width: 160px"
    @change="onChange"
  >
    <el-option
      v-for="subitem in selectOptions"
      :key="subitem.value"
      :label="subitem.label"
      :value="subitem.value"
    />
  </el-select>
</template>

<script>
export default {
  name: 'YxhySelectRemote',
  props: {
    value: {
      type: [Number, String],
      default: '',
      required: true
    },
    placeholder: {
      type: String,
      default: '请输入'
    },
    filterable: {
      type: Boolean,
      default: true
    },
    shouldCreatInit: {
      type: Boolean,
      default: true
    },
    // 请求方法
    requestFn: {
      type: Function,
      required: true
    },
    // 请求参数key
    requestKey: {
      type: String,
      required: true
    },
    // 其它请求参数
    requestOther: {
      type: Object,
      default: () => {}
    },
    // 响应key，同时也是v-modal="valueModal"绑定的值
    responseId: {
      type: String,
      required: true
    },
    responseName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      valueModal: '',
      selectOptions: []
    }
  },
  watch: {
    value: {
      handler(val) {
        this.valueModal = val
      },
      immediate: true
    }
  },
  created() {
    if (this.$props.shouldCreatInit) {
      this.remoteMethod()
    }
  },
  methods: {
    onChange(e) {
      console.log('远程搜索下拉框update:value', e)
      this.$emit('update:value', e)
    },
    remoteMethod(query) {
      this.$props.requestFn({
        [this.$props.requestKey]: query,
        ...this.$props.requestOther
      }).then(data => {
        let fulData = []
        if (Array.isArray(data)) fulData = data
        else fulData = data.data

        const arr = fulData.map(e => {
          return {
            value: e[this.$props.responseId],
            label: e[this.$props.responseName]
          }
        })
        this.selectOptions = arr
      })
    },
    reset() {
      this.valueModal = ''
      this.$emit('update:value', '')
      this.selectOptions = []
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
